<template>
  <div class="page-container">
  <div class="container">
    <!-- 标题 -->
    <h1 class="title">员工申请记录</h1>

    <!-- 申请按钮 -->
    <el-button type="primary" @click="showForm" class="add-request-button">
      添加申请
    </el-button>

    <!-- 数据表格 -->
    <el-table :data="requestsHistory.records" border style="width: 100%" v-loading="loading">
      <el-table-column prop="type" label="申请类型" width="120"></el-table-column>
      <el-table-column prop="requestReason" label="申请理由"></el-table-column>
      <el-table-column prop="startDate" label="开始日期" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.startDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="endDate" label="结束日期" width="180">
        <template #default="scope">
          <span>{{ formatDate(scope.row.endDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="approvalStatus" label="状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.approvalStatus)">{{ getStatusText(row.approvalStatus) }}</el-tag>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
        background
        layout="prev, pager, next"
        :total="pagination.total"
        :page-size="pagination.size"
        v-model:current-page="pagination.page"
        @current-change="fetchHistory"
        style="margin-top: 20px; text-align: center; "
    />
    <!-- 申请表单弹窗 -->
    <el-dialog title="添加申请" v-model="isFormVisible" width="50%" @close="resetForm">
      <el-form :model="request" label-width="120px" class="custom-form">
        <el-form-item label="申请类型" :rules="[ { required: true, message: '请选择申请类型', trigger: 'change' } ]">
          <el-select v-model="request.type" placeholder="请选择申请类型">
            <el-option label="请假" value="请假"></el-option>
            <el-option label="加班" value="加班"></el-option>
            <el-option label="离职" value="离职"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="申请理由" :rules="[ { required: true, message: '请输入申请理由', trigger: 'blur' } ]">
          <el-input type="textarea" v-model="request.requestReason" placeholder="请输入申请理由"></el-input>
        </el-form-item>

        <el-form-item v-if="request.type !== '离职'" label="开始日期">
          <el-date-picker v-model="request.startDate" type="datetime" placeholder="选择开始日期和时间"></el-date-picker>
        </el-form-item>

        <el-form-item v-if="request.type !== '离职'" label="结束日期">
          <el-date-picker v-model="request.endDate" type="datetime" placeholder="选择结束日期和时间"></el-date-picker>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitRequest">提交申请</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { ElMessage } from 'element-plus';

const requestsHistory = ref({
  records: [],
});
const pagination = ref({
  page: 1,
  size: 7,
  total: 0,
});
const loading = ref(false);
const isFormVisible = ref(false);
const currentPage = ref(1);
const request = ref({
  employeeId: '',
  type: '',
  requestReason: '',
  startDate: '',
  endDate: ''
});

const fetchHistory = async (page) => {
  loading.value = true;
  try {
    const employeeId = JSON.parse(sessionStorage.getItem('userInfo')).employeeId;
    const response = await axios.get(`http://localhost:8080/employee/checkHistory`, {
      params: { employeeId, page: pagination.value.page,
        size: pagination.value.size, }
    });
    if (response.data.code === 200) {
      requestsHistory.value.records = response.data.data.records; // 更新 records
      pagination.value.total = response.data.data.total; // 更新 total
      // requestsHistory.value.pages = response.data.data.pages; // 更新 pages
      // requestsHistory.value.current = page; // 更新 current page
    } else {
      ElMessage.error(response.data.message || '获取记录失败');
    }
  } catch (error) {
    console.error('请求历史记录失败:', error);
    ElMessage.error('请求失败');
  } finally {
    loading.value = false;
  }
};

const showForm = () => {
  isFormVisible.value = true;
  request.value.employeeId = JSON.parse(sessionStorage.getItem('userInfo')).employeeId;
};

const resetForm = () => {
  isFormVisible.value = false;
  request.value = {
    employeeId: '',
    type: '',
    requestReason: '',
    startDate: '',
    endDate: ''
  };
};

const submitRequest = async () => {
  if (!request.value.type || !request.value.requestReason) {
    ElMessage.error('请填写所有必填项！');
    return;
  }
  if (request.value.type !== '离职' && !request.value.startDate) {
    ElMessage.error('请选择开始日期！');
    return;
  }
  try {
    await axios.post('http://localhost:8080/employee/requests', request.value);
    ElMessage.success('申请提交成功');
    resetForm();
    fetchHistory(currentPage.value);
  } catch (error) {
    console.error('提交申请失败', error);
    ElMessage.error('提交申请失败');
  }
};

const handlePageChange = (page) => {
  currentPage.value = page;
  fetchHistory(page); // 获取新的分页数据
};

const getStatusText = (status) => {
  switch (status) {
    case '待审批':
      return '待审批';
    case '批准':
      return '已通过';
    case '拒绝':
      return '已拒绝';
    default:
      return '未知状态';
  }
};
// 日期格式化
const formatDate = (date) => {
  if (!date) return '';
  const d = new Date(date);
  const year = d.getFullYear();
  const month = String(d.getMonth() + 1).padStart(2, '0'); // 月份补零
  const day = String(d.getDate()).padStart(2, '0'); // 日期补零
  const hours = String(d.getHours()).padStart(2, '0'); // 小时补零
  const minutes = String(d.getMinutes()).padStart(2, '0'); // 分钟补零
  const seconds = String(d.getSeconds()).padStart(2, '0'); // 秒补零

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};

const getStatusTag = (status) => {
  switch (status) {
    case '待审批':
      return 'warning';
    case '批准':
      return 'success';
    case '拒绝':
      return 'danger';
    default:
      return '';
  }
};

onMounted(() => {
  requestsHistory.value.pages = 1;
  fetchHistory();
});

</script>

<style scoped>

.container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 20px;
}

.add-request-button {
  margin-bottom: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: center;
}


.el-table th,
.el-table td {
  text-align: center;
}



.custom-form .el-form-item {
  margin-bottom: 20px;
}


</style>
